/*
 * Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & www.dreamlu.net).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package me.boot.db.mybatis.injector;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import lombok.extern.slf4j.Slf4j;
import me.boot.common.constant.DbConst;
import me.boot.db.mybatis.injector.methods.InsertBatch;
import me.boot.db.mybatis.injector.methods.InsertIgnore;
import me.boot.db.mybatis.injector.methods.InsertIgnoreBatch;
import me.boot.db.mybatis.injector.methods.UpdateAllById;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义的 sql 注入
 */
@Slf4j
@Component
public class ExtSqlInjector extends DefaultSqlInjector {

    final static String[] UPDATE_ALL_IGNORE_COLUMNS = new String[]{
            DbConst.COLUMN_TENANT_ID,
            DbConst.COLUMN_CREATER,
            DbConst.COLUMN_UPDATER,
            DbConst.COLUMN_OWNER,
            DbConst.COLUMN_VERSION,
            DbConst.COLUMN_DELETED};

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {

        List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
        // 插入数据，如果中已经存在相同的记录，则忽略当前新数据
        methodList.add(new InsertIgnore());
        // 批量插入数据，如果中已经存在相同的记录，则忽略当前新数据
        methodList.add(new InsertIgnoreBatch());
        methodList.add(new InsertBatch());

        // UpdateAllById， 根据id完整更新目标实体
        Predicate<TableFieldInfo> predicate = field -> !StrUtil.equalsAnyIgnoreCase(field.getColumn(), UPDATE_ALL_IGNORE_COLUMNS);
        methodList.add(new UpdateAllById(predicate));

        return methodList;
    }
}
